#include "aky_com_include.h"

uint8_t fmt_uart_buf[50];

void aky_uart_set_BaudRate(uint32_t BaudRate)
{
    P04 = 1;
    P05 = 0;
    P0M = (P0M | 0x10) & ~0x20; // set bit4 and clear bit5

    S0CON = SYSUR_SM1 | SYSUR_REN; // mode1 and open uart
    SM20 = 0;                      // Disable multiprocessor communication
    S0CON2 = SYSUR_BD1;            // Baud mode form internal baud rate   BD=1  Controlled by S0RELH, S0RELL registers
    PCON = SYSUR_SMOD;             // baudrate*2  0: fcpu*1  1: fcpu*2
    S0RELH = 0x03;                 // Set baud rate
    if (BaudRate == 9600)
    {
        S0RELL = 0x98; // 0x98=9600;0xE6=38400;0xF7=115200;(Fcpu = 32M Hz)
    }
    else if (BaudRate == 38400)
    {
        S0RELL = 0xE6; // 0x98=9600;0xE6=38400;0xF7=115200;(Fcpu = 32M Hz)
    }
    else if (BaudRate == 115200)
    {
        S0RELL = 0xF7; // 0x98=9600;0xE6=38400;0xF7=115200;(Fcpu = 32M Hz)
    }
    else
    {
        S0RELL = 0x98; // 0x98=9600;0xE6=38400;0xF7=115200;(Fcpu = 32M Hz)
    }
}

void aky_uart_init(void)
{
    {
        aky_uart_set_BaudRate(9600);
    }
#if (AKY_DEBUG_PRINT_TO_SIMUL_UART == 1)
    it_simula_uart_init();
#endif
#if (AKY_DEBUG_UART_PRINTF == 1)
    aky_uart_send_string("aky_uart_init\n");
#endif
}

void aky_uart_it_callback(void)
{
    uint8_t res = 0;
    if (RI0)
    {
        RI0 = 0; // Clear Rx IRQ
    }
    res = S0BUF;
// UART_SendData(AKY_UART_CHANNEL, res);

    if (TI0)
    {
        TI0 = 0; // Clear transmit flag
    }
}

void aky_uart_send_byte(uint8_t dat)
{
    uint16_t sendcount = 0;
#if (AKY_DEBUG_PRINT_TO_SIMUL_UART == 1)
    it_simula_uart_send_byte(dat);
#endif

    S0BUF = dat;
    while (!TI0)
    {
        sendcount++;
        if (sendcount > 2000)
        {
            break;
        }
    }
    TI0 = 0;
}

void aky_uart_send_string(uint8_t *pdat)
{
    while (*pdat != '\0')
    {
        aky_uart_send_byte(*pdat);
        pdat++;
    }
}

void aky_uart_fmt_num(uint8_t *pdat, uint32_t num)
{
    aky_uart_send_string(pdat);
    sprintf(fmt_uart_buf, "%ld \n", num);
    aky_uart_send_string(fmt_uart_buf);
}

void aky_uart_fmt_hex(uint8_t *pdat, uint32_t hex)
{
    aky_uart_send_string(pdat);
    sprintf(fmt_uart_buf, "%08lx \n", hex);
    aky_uart_send_string(fmt_uart_buf);
}

void Rs232_SendByte(uint8_t dat)
{
    aky_uart_send_byte(dat);
}



//串口打印rolling code buf处理
void printf_func_rolling_code_buf_pro(void) 
{
    #if (AKY_DEBUG_UART_PRINTF == 1)
    uint16_t i;
    aky_uart_send_string("func_rolling_code_buf\n");
    aky_uart_fmt_hex("func_addr=0x", func_addr);
    // if (g_s_func.e_uart_type == UART_DEBUG)
    {
        for (i = 0; i < sizeof(u_rolling_code_buff_t); i++)
        {
            sprintf(fmt_uart_buf, "byte%02d = ",i);
            aky_uart_send_string(fmt_uart_buf);
            aky_uart_fmt_hex("0x", g_u_rolling_code_buff.rolling_code_buff[i]);
        }
    }
    #endif
}
